package com.jizhi.onework.framework.config.access;

import com.jizhi.onework.framework.model.PageConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Mapping 用户分页信息参数提取
 *
 * @author xunwu.zy
 */
public class PathPageArgumentResolver implements HandlerMethodArgumentResolver {

    private static final String PAGE_SIZE_PARAMETER = "pageSize";

    private static final String PAGE_NUM_PARAMETER = "pageNum";


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestOperation.class);
    }

    @Nullable
    @Override
    public Object resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

        if (methodParameter.hasParameterAnnotation(PathPage.class)) {
            String pageSizeStr = webRequest.getParameter(PAGE_SIZE_PARAMETER);
            String pageNumStr = webRequest.getParameter(PAGE_NUM_PARAMETER);

            int pageSize;
            if (StringUtils.isNumeric(pageSizeStr)) {
                pageSize = Math.max(1, Integer.parseInt(pageSizeStr));
            } else {
                pageSize = PageConfig.DEFAULT_PAGE_SIZE;
            }
            int pageNum;
            if (StringUtils.isNumeric(pageNumStr)) {
                pageNum = Math.max(1, Integer.parseInt(pageNumStr));
            } else {
                pageNum = PageConfig.DEFAULT_PAGE_NUM;
            }

            return new PageConfig(pageSize, pageNum);
        }
        return WebArgumentResolver.UNRESOLVED;
    }
}